package com.zw.log.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zw.commons.utlis.CheckArgument;
import com.zw.log.mapper.SysOperLogMapper;
import com.zw.log.service.SysOperLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zw.object.result.Result;
import com.zw.object.system.SysOperLog;
import com.zw.object.vo.SysOperLogQueryVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 操作日志记录 服务实现类
 * </p>
 *
 * @author zw
 * @since 2022-12-13
 */
@Service
public class SysOperLogServiceImpl extends ServiceImpl<SysOperLogMapper, SysOperLog> implements SysOperLogService {

    /**
     * 操作日志分页获取业务
     *
     * @param iPage             MP分页对象
     * @param sysOperLogQueryVo 参数实体类
     * @return Result
     */
    @Override
    public Result sysOperLogListPage(IPage<SysOperLog> iPage, SysOperLogQueryVo sysOperLogQueryVo) {
        LambdaQueryWrapper<SysOperLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(sysOperLogQueryVo.getTitle()),
                        SysOperLog::getTitle, sysOperLogQueryVo.getTitle())
                .like(StringUtils.isNotBlank(sysOperLogQueryVo.getOperName()),
                        SysOperLog::getOperName, sysOperLogQueryVo.getOperName());
        if (StringUtils.isNotBlank(sysOperLogQueryVo.getCreateTimeBegin()) && StringUtils.isNotBlank(sysOperLogQueryVo.getCreateTimeEnd())) {
            queryWrapper.and(userWrapper -> userWrapper
                    .ge(SysOperLog::getCreateTime, sysOperLogQueryVo.getCreateTimeBegin())
                    .le(SysOperLog::getCreateTime, sysOperLogQueryVo.getCreateTimeEnd()));
        }
        queryWrapper.eq(SysOperLog::getIsDeleted, 0);
        queryWrapper.orderByAsc(SysOperLog::getCreateTime);

        IPage<SysOperLog> page = baseMapper.selectPage(iPage, queryWrapper);
        return Result.ok(page);
    }

    /**
     * 异步保存操作日志业务
     *
     * @param sysOperLog 参数实体类
     */
    @Override
    @Async
    public String sysOperLogSave(SysOperLog sysOperLog) {
        int insert = baseMapper.insert(sysOperLog);
        return insert > 0 ? sysOperLog.getId() : null;
    }

    @Override
    @Async
    public void afterLog(String id, String jsonResult) {
        boolean update = lambdaUpdate()
                .set(SysOperLog::getJsonResult, jsonResult)
//                .eq(SysOperLog::getId, id)
                .update();
        CheckArgument.isTrue(update, "更新失败！");
//        throw new RuntimeException("存储错误日志！！");
    }
}
